﻿using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

using SBPweb.PhotoGallery.Common;

namespace SBPweb.PhotoGallery.Client.Logic
{

    public class AutoAdvancingGalleryList : OverridableList<AutoAdvancingGallery>
    {

        public AutoAdvancingGalleryList()
        {
        }

        public void ParseXml(string xmlSource)
        {
            DeepClear();

            XDocument xDoc = XDocument.Parse(xmlSource);
            this.AddRange(
                from gallery in xDoc.Descendants("gallery")
                select new AutoAdvancingGallery(gallery.Attribute("baseUrl").Value)
                {
                    Title = gallery.Attribute("title").Value,
                    //Items = (
                    //  from slide in gallery.Descendants("slide")
                    //  select new FetchableSlide(slide.Attribute("imageUrl").Value, slide.Attribute("thumbnailUrl").Value, slide.Attribute("caption").Value)
                    //  {
                    //  }
                    //)
                }
            );

            // needs this done in a separate loop to get the item added events invoked
            for (int i = 0; i < this.Count; i++)
            {
                this[i].Items = from slide in xDoc.Descendants("gallery").ElementAt(i).Descendants("slide")
                            select new FetchableSlide(slide.Attribute("imageUrl").Value, slide.Attribute("thumbnailUrl").Value, slide.Attribute("caption").Value)
                            {
                            };
            }
        }

        public void DeepClear()
        {
            foreach (AutoAdvancingGallery aag in this)
            {
                aag.Clear();
            }
            this.Clear();
        }

    }

}